// Copyright 2006 Mloofle Inc. All Rights Reserved.
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

/**
 * A collection of helper methods.
 */
public class Util {

  public static final int MIN_FILTER_SIZE = 8;
  public static final int STRONG_HASHES = 7;
  public static final int WEAK_HASHES = 4;

  /**
   * A fast-lookup array that determines whether a character is upper case.
   */
  private static final boolean[] IS_UPPER_CASE = new boolean[256];

  /**
   * The amount that must be added to an upper case character to make it lower
   * case.
   */
  private static final int TOLOWER_DELTA = 'a' - 'A';

  public static void close(InputStream in) {
    try {
      if (in != null) {
        in.close();
      }
    } catch (IOException e) {
      // ignore; what are you going to do?
    }
  }

  public static void close(RandomAccessFile in) {
    try {
      if (in != null) {
        in.close();
      }
    } catch (IOException e) {
      // ignore; what are you going to do?
    }
  }

  /**
   * Compute the lower case version of a word.
   * 
   * @param word the word to convert
   * @return the lower case version of the word
   */
  public static String toLowerCase(String word) {
    char[] input = word.toCharArray();
    boolean changed = false;
    for (int i = 0, len = input.length; i < len; ++i) {
      if (IS_UPPER_CASE[input[i]]) {
        changed = true;
        input[i] = (char) (input[i] + TOLOWER_DELTA);
      }
    }
    if (changed) {
      // return a new string based on the input
      return String.valueOf(input);
    }
    // just use the original
    return word;
  }

  static {
    // Initialize the upper case lookup array
    for (char i = 'A'; i <= 'Z'; ++i) {
      IS_UPPER_CASE[i] = true;
    }
  }

  public static void errExit(String msg) {
    System.err.println("ERROR: " + msg);
    System.exit(-1);
  }

}